package com.spark.lola.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.spark.lola.constant.CertificationStatus;
import com.spark.lola.constant.SupOrderStatus;
import com.spark.lola.entity.SupplierToken;
import com.spark.lola.entity.pur.OrderInfo;
import com.spark.lola.entity.pur.OrderLocation;
import com.spark.lola.entity.pur.OrderProcess;
import com.spark.lola.entity.sup.BankInfo;
import com.spark.lola.feign.LogisticsFeignService;
import com.spark.lola.feign.service.PortalServiceOpenApi;
import com.spark.lola.logistics.entity.LocationInfo;
import com.spark.lola.mapper.pur.OrderInfoMapper;
import com.spark.lola.mapper.sup.BankInfoMapper;
import com.spark.lola.request.CreateOrderRequest;
import com.spark.lola.request.UpdateOrderRequest;
import com.spark.lola.service.gds.IProductInfoService;
import com.spark.lola.service.pur.IOrderInfoService;
import com.spark.lola.support.ai.params.LicensePlateRequest;
import com.spark.lola.support.ai.service.LicensePlateService;
import com.spark.lola.support.api.entity.EnterpriseTokenUser;
import com.spark.lola.support.common.constant.CommonConstant;
import com.spark.lola.support.common.entity.ShiroUser;
import com.spark.lola.support.common.util.ResponseBean;
import com.spark.lola.support.mybatis.common.QueryCondition;
import com.spark.lola.support.mybatis.entity.PageParam;
import com.spark.lola.support.mybatis.entity.QueryParam;
import com.spark.lola.support.wms.cache.CollectionCache;
import com.spark.lola.support.wms.configuration.WmsProperties;
import com.spark.lola.support.wms.request.OrderActionRequest;
import com.spark.lola.vo.OrderVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @Author: DengYeJun
 * @Date: 2020/5/20 19:52
 */
@Api(value = "/api/order/", tags = "采购相关")
@RequestMapping("/api/order/")
@RestController
public class OrderController {
    @Autowired
    private IOrderInfoService orderInfoService;
    @Autowired
    private OrderInfoMapper orderInfoMapper;
    @Autowired
    private LogisticsFeignService logisticsFeignService;
    @Autowired
    private IProductInfoService productInfoService;
    @Autowired
    private WmsProperties wmsProperties;
    @Autowired
    private BankInfoMapper bankInfoMapper;
    @Autowired
    private LicensePlateService licensePlateService;

    @ApiOperation(value = "查询订单列表")
    @RequestMapping(value = "/",method = RequestMethod.POST, consumes = "application/json;charset=UTF-8")
    public ResponseBean index(@RequestBody QueryParam<OrderInfo> queryBean, @SessionAttribute SupplierToken tokenUser){
        QueryCondition queryCondition = new QueryCondition();
        if(queryBean.getQueryList().size()==0){
            // 过滤 已取消订单
            queryCondition.setKey("o.status");
            queryCondition.setOper("!=");
            queryCondition.setValue(SupOrderStatus.CANCELED);
            queryBean.getQueryList().add(queryCondition);
        }
        // 绑定当前供应商
        queryCondition = new QueryCondition();
        queryCondition.setKey("supplierId");
        queryCondition.setOper("=");
        queryCondition.setValue(tokenUser.getSupplierId());
        queryBean.getQueryList().add(queryCondition);
        // 过滤 已回收订单
        queryCondition = new QueryCondition();
        queryCondition.setKey("o.status");
        queryCondition.setOper("!=");
        queryCondition.setValue(SupOrderStatus.DUSTBIN);
        queryBean.getQueryList().add(queryCondition);

        PageParam<OrderInfo> pageParam = queryBean.toPageParam();

        IPage<OrderInfo> page = orderInfoMapper.page(pageParam.getPage(), pageParam.getEntityWrapper());
        return ResponseBean.success(page);
    }

    @ApiOperation(value = "查询订单详情")
    @RequestMapping(value = "/detail/{id}", method = RequestMethod.POST)
    public ResponseBean detail(@PathVariable Long id,
                                 @SessionAttribute SupplierToken tokenUser){
        OrderVo vo =new OrderVo();
        OrderInfo orderInfo = orderInfoService.findFullById(id);
        List<OrderProcess> logs = orderInfoService.logs(id);
        vo.setOrderInfo(orderInfo);
        vo.setLogs(logs);
        return ResponseBean.success(vo);
    }

    @ApiOperation(value = "查询订单日志")
    @ApiImplicitParam(name = "id",paramType = "path",required = true)
    @RequestMapping(value = "/log/{id}", method = RequestMethod.POST)
    public ResponseBean log(@PathVariable Long id,
                            @SessionAttribute SupplierToken tokenUser){
        return ResponseBean.success(orderInfoService.logs(id));
    }

    @ApiOperation(value = "查询业务员列表")
    @RequestMapping(value = "/salesman", method = RequestMethod.POST)
    public ResponseBean salesman(@SessionAttribute SupplierToken tokenUser){
        Long dutyId = wmsProperties.getPurchase().getDutyId().get(1);
        return ResponseBean.success(CollectionCache.dutyEmployees.get(dutyId));
    }

    @ApiOperation(value = "查询纸厂列表")
    @RequestMapping(value = "/company", method = RequestMethod.POST)
    public ResponseBean company(){
        List<LocationInfo> lst = logisticsFeignService.getCompany();
        return ResponseBean.success(lst);
    }

    @ApiOperation(value = "查询收款列表")
    @RequestMapping(value = "/bank", method = RequestMethod.POST)
    public ResponseBean bank(@SessionAttribute SupplierToken tokenUser){
        QueryWrapper<BankInfo> query =new QueryWrapper<>();
        query.eq("supplier_id",tokenUser.getSupplierId());
        query.eq("used", CommonConstant.Y);
        query.orderByDesc("auto");
        List<BankInfo> lst = bankInfoMapper.selectList(query);
        return ResponseBean.success(lst);
    }

    @ApiOperation(value = "查询货品列表")
    @RequestMapping(value = "/product", method = RequestMethod.POST)
    public ResponseBean product(){
        return ResponseBean.success(productInfoService.selectMap(1L,null));
    }

    @ApiOperation(value = "创建采购单")
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    @Transactional(rollbackFor = Exception.class)
    public ResponseBean create(@RequestBody CreateOrderRequest request, @SessionAttribute SupplierToken tokenUser) throws Exception {
        if(!tokenUser.getCertificationStatus().equals(CertificationStatus.SUCCESS)){
            return ResponseBean.error("非法操作!");
        }
        OrderInfo form = new OrderInfo();
        BeanUtils.copyProperties(request, form);
        form.setSupplierId(tokenUser.getSupplierId());
        form.setCreator(tokenUser.getUsername());
        form.setUpdator(tokenUser.getUsername());
        OrderInfo model = orderInfoService.add(form, tokenUser.getShiroUser());
        return ResponseBean.success(model);
    }

    @ApiOperation(value = "修改货品明细")
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    @Transactional(rollbackFor = Exception.class)
    public ResponseBean update(@RequestBody UpdateOrderRequest request, @SessionAttribute SupplierToken tokenUser) throws Exception{
        OrderInfo form = new OrderInfo();
        BeanUtils.copyProperties(request, form);
        OrderInfo model = orderInfoService.update(form, tokenUser.getShiroUser());
        return ResponseBean.success(model);
    }

    @ApiOperation(value = "修改地址")
    @RequestMapping(value = "/update-location", method = RequestMethod.POST)
    @Transactional(rollbackFor = Exception.class)
    public ResponseBean updateLocation(@RequestBody OrderLocation request) throws Exception {
        if (!orderInfoService.updateLoaction(request)) {
            return ResponseBean.error("保存失败!");
        }
        return ResponseBean.success(request);
    }

    @ApiOperation(value = "识别车牌号")
    @RequestMapping(value = "/check-license-plate", method = RequestMethod.POST)
    public ResponseBean checkLicensePlate(@RequestBody LicensePlateRequest request, @SessionAttribute SupplierToken tokenUser) throws Exception {
        return licensePlateService.discern(0,request.getBase64Image());
    }

    @ApiOperation(value = "发货")
    @RequestMapping(value = "/checking", method = RequestMethod.POST)
    @Transactional(rollbackFor = Exception.class)
    public ResponseBean checking(@RequestBody OrderActionRequest request,@SessionAttribute SupplierToken tokenUser) throws Exception {
        orderInfoService.checking(request, tokenUser.getShiroUser());
        return ResponseBean.success();
    }

    @ApiOperation(value = "取消订单")
    @RequestMapping(value = "/canceling", method = RequestMethod.POST)
    @Transactional(rollbackFor = Exception.class)
    public ResponseBean canceling(@RequestBody OrderActionRequest request, @SessionAttribute SupplierToken tokenUser) throws Exception {
        orderInfoService.canceling(request,tokenUser.getShiroUser());
        return ResponseBean.success();
    }

    @ApiOperation(value = "加入垃圾箱")
    @RequestMapping(value = "/recycle/{id}", method = RequestMethod.POST)
    @Transactional(rollbackFor = Exception.class)
    public ResponseBean recycle(@PathVariable Long id,
                                @SessionAttribute SupplierToken tokenUser) throws Exception {
        orderInfoService.recycle(id,tokenUser.getShiroUser());
        return ResponseBean.success();
    }


}
